package dailytest;

import entity.Inventory;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: youdao.hww
 * @Date: 10/28/24
 * @Desc:
 */
public class InventoryTest {

    public static void main(String[] args) {
        Inventory one = Inventory.builder().id(1).currentNum(BigDecimal.valueOf(5)).build();
        Inventory two = Inventory.builder().id(2).currentNum(BigDecimal.valueOf(-1)).build();
        Inventory three = Inventory.builder().id(3).currentNum(BigDecimal.valueOf(2)).build();
        Inventory four = Inventory.builder().id(4).currentNum(BigDecimal.valueOf(3)).build();
        List<Inventory> inventoryList = Arrays.asList(one, two, three, four);



        List<Inventory> lessZeroStock = inventoryList.stream().filter(f -> f.getCurrentNum().compareTo(BigDecimal.ZERO) < 0).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(lessZeroStock)) {

            List<Inventory> greaterZeroStock = inventoryList.stream().filter(f -> f.getCurrentNum().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());

            for (Inventory lessStock : lessZeroStock) {
                for (Inventory greaterStock : greaterZeroStock) {
                    // 需多次扣减
                    if (lessStock.getCurrentNum().abs().compareTo(greaterStock.getCurrentNum()) > 0) {
                        lessStock.setCurrentNum(lessStock.getCurrentNum().add(greaterStock.getCurrentNum()));
                        greaterStock.setCurrentNum(greaterStock.getCurrentNum().subtract(greaterStock.getCurrentNum()));
                    } else {
                        // 一次扣减
                        greaterStock.setCurrentNum(greaterStock.getCurrentNum().add(lessStock.getCurrentNum()));
                        lessStock.setCurrentNum(BigDecimal.ZERO);
                    }
                }
            }
            greaterZeroStock.addAll(lessZeroStock);
            // 抵消后的库存
            inventoryList = new ArrayList<>(greaterZeroStock);

            System.out.println("inventoryList = " + inventoryList);
        }


    }


}
